import { CallHandler, ExecutionContext, Injectable, NestInterceptor,HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { map, Observable } from 'rxjs';

@Injectable()
export class FormatResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const response = context.switchToHttp().getResponse<Response>();
    const req = context.switchToHttp().getRequest()
    return next.handle().pipe(map((data) => {
      //post返回的状态码是201 这里统一修改为200
      if (req.method === 'POST') {
        if (response.statusCode === HttpStatus.CREATED) {
          response.status(HttpStatus.OK);
        }
      }
      return {
        code: response.statusCode,
        message: 'success',
        data
      }
    }));
  } 
}

